layui.use(['layer', 'table', 'form'], function () {
    let layer = layui.layer,
        form = layui.form,
        table = layui.table;
    layui.layer.load(0, {shade: [0.5, '#fff']});

    /*查询所有收件箱的信息*/
    table.render({
        elem: '#inBox-table'
        , toolbar: '#email-table-toolbar'
        , height: 600
        , where: {type: 1, userName: USERNAME}
        , url: '/getEmail'
        , cols: [
            [ //标题栏
                {field: 'id', title: '编号', width: 60, align: 'center'},
                {field: 'title', title: '标题', width: 120, align: 'center'},
                {field: 'sendName', title: '发件人', width: 100, align: 'center'},
                {field: 'sendNo', title: '发件人学号/工号', width: 150, align: 'center'},
                {field: 'sendEmail', title: '发件人邮箱', width: 170, align: 'center'},
                {field: 'creatTime', title: '收件时间', width: 170, align: 'center'},
                {field: 'content', title: '邮件内容', align: 'center'},
                {field: 'state', title: '状态', width: 80, align: 'center'},
                {title: '操作', align: 'center', width: 80, toolbar: '#email-table-tool'}
            ]
        ]
        , done: function (res, curr, count) {
            $("#inBox-sum").html(count)
        }
        // ,skin: 'line' //表格风格
        , even: true
        , page: true
        , limits: [11, 22, 33]
        , limit: 11
        , text: {
            none: '<div class="layui-anim layui-anim-scaleSpring"  style="margin-top: 150px"><i class="layui-icon" style="color: #009f95;font-size: 150px;border-bottom: #009f95 solid 2px;padding:15px;margin-top: 50px" >&#xe664;</i><br>' +
                '<br><br><br><br><div class="layui-text" style="font-size: 25px;margin-top: 25px;color: #009f95">好像没有没找到数据呢</div></div>'
            ,
            error: '<div style="margin-top: 150px"><i class="layui-icon" style="color: #009f95;font-size: 150px;border-bottom: #009f95 solid 2px;padding:15px;margin-top: 50px" >&#xe664;</i><br>' +
                '<br><div class="layui-text" style="font-size: 25px;margin-top: 25px;color: #009f95">好像没有出错了呢</div></div>'
        }
    });


    //监听所有收件箱表头事件  监听对象 inBox-table
    table.on('toolbar(inBox-table)', function (obj) {
        //查询事件
        if (obj.event === 'queryEmail') {  //按关键字搜索事件
            let queryKey = $('#queryKey').val().trim(); //获取搜索的关键字
            if (queryKey === null || queryKey === '') {
                layer.msg('请输入要查询内容', {offset: '250px', time: 1500, anim: 6, area: ['200px', '50px']});
                return false;
            }
            emailTableLoad('inBox-table', queryKey, 1);

        } else if (obj.event === 'queryAll') {  //查询全部
            emailTableLoad('inBox-table', '', 1);
        }
    });


    /*监听所有收件箱操作栏事件 监听对象 inBox-table*/
    table.on('tool(inBox-table)', function (obj) {
        let data = obj.data;  //json格式的数据
        if (obj.event === 'detail') {  //编辑事件
            layer.open({
                type: 1
                , offset: 100
                , skin: 'layui-layer-rim'
                , area: ['540px', '550px']
                , content: $("#email-detail")
                , title: '邮件详情内容'
                , success: function (layerObj) {
                    $(".layui-layer-shade").appendTo(layerObj.parent());
                    setEmailDetail(data, 1, obj);
                }
                , end: function () {
                    $("#email-detail").css("display", 'none');
                }
            });
        }
    });


    /*查询所有发件箱的信息 */
    table.render({
        elem: '#outBox-table'
        , toolbar: '#email-table-toolbar'
        , height: 600
        , initSort: {field: 'id', type: 'desc'}
        , where: {type: 2, userName: USERNAME}
        , url: '/getEmail'
        , cols: [
            [ //标题栏
                {field: 'id', title: '编号', width: 60, align: 'center'},
                {field: 'title', title: '标题', width: 120, align: 'center'},
                {field: 'receiveName', title: '收件人', width: 100, align: 'center'},
                {field: 'receiveNo', title: '收件人学号/工号', width: 150, align: 'center'},
                {field: 'receiveEmail', title: '收件人邮箱', width: 170, align: 'center'},
                {field: 'creatTime', title: '发件时间', width: 170, align: 'center'},
                {field: 'content', title: '邮件内容', align: 'center'},
                {field: 'state', title: '状态', width: 80, align: 'center'},
                {title: '操作', align: 'center', width: 80, toolbar: '#email-table-tool'}
            ]
        ]
        , done: function (res, curr, count) {
            $("#outBox-sum").html(count)
        }
        , even: true
        , page: true
        , limits: [11, 22, 33]
        , limit: 11
        , text: {
            none: '<div class="layui-anim layui-anim-scaleSpring"  style="margin-top: 150px"><i class="layui-icon"  style="color: #009f95;font-size: 150px;border-bottom: #009f95 solid 2px;padding:15px;margin-top: 50px" >&#xe664;</i><br>' +
                '<br><br><br><br><div class="layui-text" style="font-size: 25px;margin-top: 25px;color: #009f95">好像没有没找到数据呢</div></div>'
            ,
            error: '<div style="margin-top: 150px"><i class="layui-icon"  style="color: #009f95;font-size: 150px;border-bottom: #009f95 solid 2px;padding:15px;margin-top: 50px" >&#xe664;</i><br>' +
                '<br><div class="layui-text" style="font-size: 25px;margin-top: 25px;color: #009f95">好像没有出错了呢</div></div>'
        }
    });


    //监听所有发件箱表头事件  监听对象 outBox-table
    table.on('toolbar(outBox-table)', function (obj) {

        //查询事件
        if (obj.event === 'queryEmail') {  //按关键字搜索事件
            let queryKey = $('#queryKey').val().trim(); //获取搜索的关键字
            if (queryKey === null || queryKey === '') {
                layer.msg('请输入要查询内容', {offset: '250px', time: 1500, anim: 6, area: ['200px', '50px']});
                return false;
            }
            emailTableLoad('outBox-table', queryKey, 2);
        } else if (obj.event === 'queryAll') {  //查询全部
            emailTableLoad('outBox-table', '', 2);
        }
    });


    //监听所有发件箱操作栏事件 监听对象 outBox-table
    table.on('tool(outBox-table)', function (obj) {
        let data = obj.data;  //json格式的数据
        if (obj.event === 'detail') {  //编辑事件
            layer.open({
                type: 1
                , offset: 100
                , skin: 'layui-layer-rim'
                , area: ['540px', '550px']
                , content: $("#email-detail")
                , title: '邮件详情内容'
                , success: function (layerObj) {
                    $(".layui-layer-shade").appendTo(layerObj.parent());
                    setEmailDetail(data, 2, obj);
                }
                , end: function () {
                    $("#email-detail").css("display", 'none');
                }
            });
        }
    });


    /*我要写一封新的邮件*/
    $("#write-email-btn").click(function () {
        layer.open({
            type: 1
            , offset: 20
            , skin: 'layui-layer-rim'
            , area: ['750px', '720px']
            , content: $("#write-email")
            , title: '发送一封新邮件'
            , fixed: false
            , success: function (layero) {
                let mask = $(".layui-layer-shade");
                mask.appendTo(layero.parent());
            }
            , end: function () {
                $("#write-email").css("display", 'none');
            }
        });

    });

    /*发送一封邮件*/
    form.on('submit(send-email-btn)', function (data) {
        console.log(data.elem) //被执行事件的元素DOM对象，一般为button对象
        console.log(data.form) //被执行提交的form对象，一般在存在form标签时才会返回
        console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
        let emailData = JSON.stringify(data.field);
        let loadPage = layui.layer.load(0, {shade: [0.5, '#fff']});
        $.ajax({
            url: "/writeEmail",
            type: 'post',
            data: {
                emailData: emailData, userName: USERNAME
            },
            dataType: 'json',
            success: function (data) {  //调用接口成功
                if (data === 1001 || data === '1001') {
                    layer.close(loadPage);
                    layer.closeAll('page');
                    layui.layer.msg('发送成功！', {offset: '300px', time: 2500, anim: 0});
                    emailTableLoad('outBox-table', '', 2);
                } else if (data === 1002 || data === '1002') {
                    layui.layer.close(loadPage);
                    layui.layer.alert('收件人不存在！');
                } else if (data === 1004 || data === '1004') {
                    layui.layer.close(loadPage);
                    layui.layer.alert('邮箱授权码未设置，或授权码设置错误，请前往个人中心邮箱进行设置或者修改！');
                } else {
                    layui.layer.close(loadPage);
                    layui.layer.alert('授权码设置错误，请前往个人中心邮箱进行设置更新你的邮箱授权码');
                }
            },
            error: function () {  //接口错误
                layui.layer.close(loadPage);
                layui.layer.alert('服务器出错啦,请稍后再试！');
            }
        });
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });

    //切换收发邮件箱
    $("#inBox").click(function () {
        $("#show-in-box").show();
        $("#show-out-box").hide();
    });

    $("#outBox").click(function () {
        $("#show-in-box").hide();
        $("#show-out-box").show();
    });


    //右边的菜单栏
    $("#drafts").click(function () {
        layer.msg('功能努力开发中', {offset: '250px', time: 1500, anim: 0, area: ['200px', '50px']});
    });

    $("#linkMan").click(function () {
        layer.msg('功能努力开发中', {offset: '250px', time: 1500, anim: 0, area: ['200px', '50px']});
    });

    $("#gifts").click(function () {
        layer.msg('功能努力开发中', {offset: '250px', time: 1500, anim: 0, area: ['200px', '50px']});
    });

    $("#recycleBox").click(function () {
        layer.msg('功能努力开发中', {offset: '250px', time: 1500, anim: 0, area: ['200px', '50px']});
    });


    layui.layer.closeAll('loading');

});


//邮件表格重载
function emailTableLoad(tableName, queryKey, type) {
    layui.table.reload(tableName, {
        where: {queryKey: queryKey, type: type, userName: USERNAME} //设定异步数据接口的额外参数
    });
}

//设置显示邮件的详情
function setEmailDetail(data, type, obj) {
    if (type === 1 || type === '1') {
        // type 为1 是收件箱 每次打开收件箱的时候对 是否已读做出一个判断
        //如果是未读则修改状态为已读
        if (data.state === '未读') {
            let url = "updateEmail";
            let param = {id: data.id}
            $.get(url, param, function (data) {
                if (data === true || data === "true") {
                    obj.update({
                        state: '已读'
                    });
                }
            });
        }
        $("#email-mane").html(data.sendName);
        $("#email-no").html(data.sendNo);
        $("#email-time").html(data.creatTime);
        $("#set-name").html('发件人姓名:');
        $("#set-no").html('发件人学号/工号:');
        $("#email-email").html(data.sendEmail);
        $("#email-email1").html("发件人邮箱");
    } else if (type === 2 || type === '2') {
        $("#email-mane").html(data.receiveName);
        $("#email-no").html(data.receiveNo);
        $("#email-time").html(data.creatTime);
        $("#set-name").html('收件人姓名:');
        $("#set-no").html('收件人学号/工号:');
        $("#email-email").html(data.receiveEmail);
        $("#email-email1").html("收件人邮箱");
    }
    $("#email-id").html(data.id);
    $("#email-title").html(data.title);
    $("#email-content").html(data.content);
}

